package com.xxwy.queue;

import java.awt.*;
import java.util.Arrays;

/**
 * @author xxwy
 * 使用循环队列，解决因为使用数组的形式，队首出，其他数据要移位so时间复杂度是O（n）
 * 循环队列：
 * front 数组中的第一个元素, tail 数组的中对列的最后一个元素
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] data;
    /**
     * 队首
     */
    private int front;
    /**
     * 队尾，有意识的浪费一个条件保证如果
     * front== tail 队空
     * （tail+1）% capacity == front 队列满
     */
    private int tail;

    private int size;

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public E getFront() {
        return data[front];
    }

    @Override
    public int getCapacity() {
        return data.length - 1;
    }

    /**
     * 出队
     *
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("队列为Empty");
        }
        E e = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        //缩容
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return e;
    }

    /**
     * 入队
     *
     * @param e
     */
    @Override
    public void enqueue(E e) {
        //判断队列是不是满的
        if ((tail + 1) % data.length == front) {
            //扩容
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        size++;
        tail = (tail + 1) % data.length;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(front + i) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d, capacity = %d\n", size, getCapacity()));
        res.append("front[ ");
        for (int i = front; i !=tail; i=(i+1)%data.length) {
            res.append(data[i]);
            if ((i +1)%data.length != tail) {
                res.append(", ");
            }
        }
        res.append(" ]tail");
        return res.toString();
    }
}
